package com.designoutput.ui.gallery
{
	import com.designoutput.ui.newControls.ControlBase;
	import com.designoutput.utils.Globals;
	import com.designoutput.vo.GalleryImageVo;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.DataEvent;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;

	/**
	 * The image element use to load image for gallery.
	 */
	[Event(name="ImageLoaded", type="flash.events.DataEventE")]
	public class ImageHolder extends ControlBase
	{	
		private var _imageVo:GalleryImageVo;		
		private var _loader:Loader;
		private var _maxScaleX:Number = -1;
		private var _maxScaleY:Number = -1;
		public var imageBody:DisplayObject;	
		
		override protected function initialize():void {			
			super.initialize();
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadedHandler);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
		}
		
		override protected function updateDisplay():void {
			super.updateDisplay();
			
			if(imageBody != null){
				if(imageBody.scaleY <= _maxScaleX)
					imageBody.x = ( _width - imageBody.width ) / 2;
				else 
					imageBody.x = 0;				
				
				if(imageBody.scaleY <= _maxScaleY)
					imageBody.y = ( _height - imageBody.height ) / 2;
				else 
					imageBody.y = 0;
			}
		}
		
		public function updateImageBody():void {
			updateDisplay();
		}			
		
		public function get imageVo():GalleryImageVo {
			return _imageVo;
		}
		
		public function set imageVo(vo:GalleryImageVo):void
		{
			_imageVo = vo;
			_loader.load(new URLRequest(Globals.applicationUrl + vo.url));
		}

		public function loadedHandler(evt:Event):void
		{
			imageBody = _loader.content;
			if(imageBody is Bitmap)
				(imageBody as Bitmap).smoothing = true;
			
			this.addChild(imageBody);
			
			invalidateDisplay();
			dispatchEvent(new DataEvent("ImageLoaded",true,false,imageBody.height.toString() + "_" + imageBody.width.toString()));
		}

		public function errorHandler(evt:Event):void
		{
			trace("ImageItem::errorHandler");
			this.dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, ErrorEvent(evt).text));
		}

		public function get maxScaleX():Number
		{
			return _maxScaleX;
		}

		public function set maxScaleX(value:Number):void
		{
			_maxScaleX = value;
		}

		public function get maxScaleY():Number
		{
			return _maxScaleY;
		}

		public function set maxScaleY(value:Number):void
		{
			_maxScaleY = value;
		}
	}
}